<?php

namespace app\api\controller\shop;


use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shopdevice;
use app\admin\model\Shoproom;
use app\admin\model\Shoproomset;
use app\common\controller\Api;
use fast\Http;
use OSS\OssClient;
use think\Config;

/**
 *
 */
class Room extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {

        $this->success('请求成功');
    }


    /**
     * 房间打扫记录
     */
    public function cleanHistory()
    {

        $shop_id = $this->request->param('shop_id');
        $user_id = $this->request->param('user_id');
        $status = $this->request->param('status');
        $where = array();
        $where['shop_id'] = $shop_id;

        if ($user_id != '') {
            $where['user_id'] = $user_id;
        }
        if ($status != '') {
            $where['status'] = $status;
        }

        $roomCleanModel = new Roomclean();
        $time = strtotime("-1 day", time());
        $list = $roomCleanModel->with(['room'])->where("start_time", '>', $time)->where($where)->order('start_time', 'desc')->select();
        foreach ($list as $key => $val) {
            $list[$key]['room']['logo'] = cdnurl($val['room']['logo'], true);
            $list[$key]['start_time_txt'] = date("Y-m-d H:i", $val['start_time']);
            $list[$key]['end_time_txt'] = date("Y-m-d H:i", $val['end_time']);
            $minute = floor(($val['end_time'] - $val['start_time']) % 86400 / 60);
            $list[$key]['min'] = $minute;

            $list[$key]['status_txt'] = $roomCleanModel->getStatus($val['status']);
        }
        $this->success('', $list);
    }


    /**
     * 套餐列表
     */

    public function setList()
    {

        $shop_id = $this->request->param('shop_id');

        $shopRoomSetModel = new Shoproomset();
        $list = $shopRoomSetModel->with(['room'])->where('Shoproomset.shop_id', $shop_id)->group('room_id')->select();
        $data = array();
        foreach ($list as $key => $val) {
            $roomList = $shopRoomSetModel->where('room_id', $val['room_id'])->order('hour', 'asc')->select();
            $obj = array();
            $obj['name'] = $val['room']['name'];
            $obj['id'] = $val['room']['id'];

            $obj['set'] = $roomList;
            $data[] = $obj;
        }

        $this->success('', $data);

    }

    /**
     * 套餐添加
     */
    public function addRoomSet()
    {
        $room_id = $this->request->param('id');
        $set = $this->request->param('set');

        $shopRoomModel = new Shoproom();
        $shopRoomSetModel = new Shoproomset();
        $room = $shopRoomModel->where('id', $room_id)->find();
        $shop_id = $room['shop_id'];

        $set = json_decode(htmlspecialchars_decode($set), true);

        $db = array();
        foreach ($set as $key => $val) {
            $obj = array();
            //套餐时长不能低于1小时
            if ($val['hour'] < 1) {
                $this->error("套餐的时长不能低于1小时");
            }
            if ($val['id'] == -1) {

                if ($val['hour'] * 6 > $val['amount']) {

                    $this->error("套餐的价格设置过低");
                    break;
                } else {

                    if ($val['name'] != "") {
                        $obj['name'] = $val['name'];
                        $obj['time'] = $val['time'];
                        $obj['end_time'] = $val['end_time'];
                    } else {
                        $obj['name'] = $val['hour'] . "小时套餐";

                    }
                    $obj['shop_id'] = $shop_id;
                    $obj['room_id'] = $room_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $shopRoomSetModel->insert($obj);
                }

            } else {

                if ($val['hour'] * 6 > $val['amount']) {

                    $this->error("套餐的价格设置过低");
                    break;
                } else {
                    if($val['time'] == ''){
                        $obj['name'] = $val['hour'] . "小时套餐";
                    }else{
                        $obj['name'] = $val['name'];
                        $obj['time'] = $val['time'];
                        $obj['end_time'] = $val['end_time'];
                    }
                    $obj['shop_id'] = $shop_id;
                    $obj['room_id'] = $room_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $shopRoomSetModel->where('id', $val['id'])->update($obj);
                }

            }

        }
        $this->success('成功');

    }

    /**
     * 套餐添加
     */
    public function addRoomSet2()
    {
        $room_id = $this->request->param('id');
        $set = $this->request->param('set');

        $shopRoomModel = new Shoproom();
        $shopRoomSetModel = new Shoproomset();
        $room = $shopRoomModel->where('id', $room_id)->find();
        $shop_id = $room['shop_id'];

        $set = json_decode(htmlspecialchars_decode($set), true);

        $db = array();
        foreach ($set as $key => $val) {
            $obj = array();
            if ($val['id'] == -1) {

                if ($val['hour'] * 6 < $val['amount']) {


                    $this->error("套餐的价格设置过低");
                    break;
                } else {
                    $obj['shop_id'] = $shop_id;
                    $obj['room_id'] = $room_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $obj['weigh'] = $val['weigh'];
                    $obj['name'] = $val['hour'] . "小时套餐";
                    $shopRoomSetModel->insert($obj);
                }

            } else {
                if ($val['hour'] * 6 < $val['amount']) {


                    $this->error("套餐的价格设置过低");
                    break;
                } else {
                    $obj['shop_id'] = $shop_id;
                    $obj['room_id'] = $room_id;
                    $obj['hour'] = $val['hour'];
                    $obj['amount'] = $val['amount'];
                    $obj['weigh'] = $val['weigh'];
                    $obj['name'] = $val['hour'] . "小时套餐";
                    $shopRoomSetModel->where('id', $val['id'])->update($obj);
                }


            }


        }
        $this->success('成功');

    }

    /**
     * 包厢列表
     */
    public function getRoomList()
    {

        $shop_id = $this->request->param('shop_id');
        $status = $this->request->param('status');
        $bind = $this->request->param('bind');

        $where = array();
        $where['shop_id'] = $shop_id;

        if ($status != 0) {
            if ($status == 1) {//空闲
                $where['status'] = 'free';
            } else if ($status == 2) {//使用中
                $where['status'] = 'busy';
            } else if ($status == 3) {//打扫中
                $where['status'] = 'clean';
            }
        }
        if ($bind != 0) {
            if ($bind == 1) {
                $where['is_bind'] = 1;
            } else {
                $where['is_bind'] = -1;
            }
        }

        $shopRoomModel = new Shoproom();
        $list = $shopRoomModel->where($where)->select();
        foreach ($list as $key => $val) {
            $list[$key]['logo'] = cdnurl($val['logo'], true);
            $list[$key]['check'] = true;

        }
        $this->success('', $list);
    }

    //保洁端新的列表，包含台桌管理
    public function getAllList()
    {

        $shop_id = $this->request->param('shop_id');
        $status = $this->request->param('status');
        $bind = $this->request->param('bind');

        $newDb = array();
        $shopRoomModel = new Shoproom();
        $roomList = $shopRoomModel->where('shop_id', $shop_id)->select();
        foreach ($roomList as $key => $val) {
            $roomList[$key]['logo'] = cdnurl($val['logo'], true);
        }
        $newDb['room'] = $roomList;

        $shopTableModel = new \app\admin\model\Shoptable();
        $tableList = $shopTableModel->where('shop_id', $shop_id)->select();
        $is_table = false;

        $newDb['table'] = [];
        if (!empty($tableList)) {
            $is_table = true;
            foreach ($tableList as $key => $val) {
                $tableList[$key]['logo'] = cdnurl($val['logo'], true);
            }
            $newDb['table'] = $tableList;
        }
        $newDb['is_table'] = $is_table;
        $newDb['code']=1;

        return json($newDb);
    }


    public function roomDetail()
    {

        $id = $this->request->param('room_id');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tags = explode(",", $room['tag']);
        $coverList = array();
        if ($room['cover'] != '') {
            $covers = explode(",", $room['cover']);

            foreach ($covers as $key => $val) {
                $obj = array();
                $obj['cover'] = $val;
                $obj['cover_url'] = cdnurl($val, true);
                $coverList[] = $obj;
            }
        }

        $room['coverList'] = $coverList;
        $room['tagList'] = $tags;
        $room['status_txt'] = $shopRoomModel->getStatus($room['status']);
        $room['logo_url'] = cdnurl($room['logo'], true);

        $this->success('', $room);
    }

    public function updateRoom()
    {

        $id = $this->request->param('room_id');


        $name = $this->request->param('name');
        $logo = $this->request->param('logo');
        $status = $this->request->param('status');
        $cover = $this->request->param('cover');
        $hour_price = $this->request->param('hour_price');
        $min_book_hour = $this->request->param('min_book_hour');
        $weigh = $this->request->param('weigh');
        $book_score = $this->request->param('book_score');
        $back_score = $this->request->param('back_score');

        $tag = $this->request->param('tag');
        $shopRoomModel = new \app\admin\model\Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $db = array();
        if ($name != '') {
            $db['name'] = $name;
        }
        if ($book_score != '') {
            $db['book_score'] = $book_score;
        }
        if ($back_score != '') {
            $db['back_score'] = $back_score;
        }
        if ($logo != '') {
            $db['logo'] = $logo;
        }
        if ($status != '') {

            if ($status == 'free' || $status == 'stop') {
                $db['status'] = $status;
            } else {
                $shopRoomModel->where('id', $id)->update(['is_clean' => 1]);
            }


        }
        if ($weigh != '') {
            $db['weigh'] = $weigh;
        }
        if ($hour_price != '') {
            $db['hour_price'] = $hour_price;
        }
        if ($min_book_hour != '') {
            $db['min_book_hour'] = $min_book_hour;

        }
        if ($tag != '') {
            $tagList = explode(",", $room['tag']);
            $isAdd = true;
            foreach ($tagList as $key => $val) {
                if ($val == $tag) {
                    $isAdd = false;
                }
            }
            if ($isAdd) {
                $tag = $room['tag'] . "," . $tag;
                $db['tag'] = $tag;
            }

        }

        if ($cover != '') {
            $str = $room['cover'] . "," . $cover;
            $db['cover'] = $str;
        }
        $shopRoomModel->where('id', $id)->update($db);
        $this->success('成功');

    }


    public function removeRoomTag()
    {

        $room_id = $this->request->param('room_id');

        $tagStr = $this->request->param('tag');

        $shopRoomModel = new \app\admin\model\Shoproom();
        $room = $shopRoomModel->where('id', $room_id)->find();


        if ($room['tag'] != "") {
            $tags = explode(",", $room['tag']);
        } else {
            $tags = [];
        }
        $tagList = array();
        foreach ($tags as $key => $val) {
            if ($val != $tagStr) {
                $tagList[] = $val;
            }
        }
        $str = "";
        foreach ($tagList as $key => $val) {
            $str = $str . $val;
            if ($key != count($tagList) - 1) {
                $str = $str . ",";
            }
        }
        $db = array();
        $db['tag'] = $str;
        $shopRoomModel->where('id', $room_id)->update($db);
        $this->success('成功');
    }


    /**
     * 移除封面
     */
    public function removeRoomCover()
    {
        $room_id = $this->request->param('room_id');
        $coverStr = $this->request->param('cover');

        $shopRoomModel = new \app\admin\model\Shoproom();
        $room = $shopRoomModel->where('id', $room_id)->find();

        $cover = explode(",", $room['cover']);
        $covers = array();
        foreach ($cover as $key => $val) {
            if ($val != $coverStr) {
                $covers[] = $val;
            }
        }
        $str = "";
        foreach ($covers as $key => $val) {
            $str = $str . $val;
            if ($key != count($covers) - 1) {
                $str = $str . ",";
            }
        }
        $db = array();
        $db['cover'] = $str;
        $shopRoomModel->where('id', $room_id)->update($db);
        $this->success('成功');

    }

    public function addRoom()
    {

        $shop_id = $this->request->param('shop_id');
        $name = $this->request->param('name');
        $hour_price = $this->request->param('hour_price');
        $min_book_hour = $this->request->param('min_book_hour');
        $tag = $this->request->param('tag');
        $logo = $this->request->param('logo');
        $cover = $this->request->param('cover');
        $weigh = $this->request->param('weigh');

        $tag = json_decode(htmlspecialchars_decode($tag), true);
        $cover = json_decode(htmlspecialchars_decode($cover), true);

        $contentUrl = "";
        foreach ($cover as $key => $val) {
            $contentUrl = $contentUrl . $val;
            if ($key != count($cover) - 1) {
                $contentUrl = $contentUrl . ",";
            }
        }

        $tagStr = "";
        foreach ($tag as $key => $val) {
            $tagStr = $tagStr . $val;
            if ($key != count($tag) - 1) {
                $tagStr = $tagStr . ",";
            }
        }

        $db = array();
        $db['shop_id'] = $shop_id;
        $db['name'] = $name;
        $db['hour_price'] = $hour_price;
        $db['min_book_hour'] = $min_book_hour;
        $db['is_bind'] = -1;
        $db['status'] = 'free';
        $db['logo'] = $logo;
        $db['tag'] = $tagStr;
        $db['cover'] = $contentUrl;
        $db['weigh'] = $weigh;


        $shopRoomModel = new Shoproom();
        $id = $shopRoomModel->insertGetId($db);
        if ($id) {
            $this->success('成功');
        } else {
            $this->error("添加失败");
        }
    }

    /**
     * 获取房间套餐
     */
    public function getRoomSet()
    {
        $room_id = $this->request->param('room_id');
        $sale = $this->request->param('sale');
        $shopRoomSetModel = new Shoproomset();
        if ($sale != "") {
            $list = $shopRoomSetModel->where('time', "<>", '')->where('room_id', $room_id)->order('hour', 'asc')->select();
        } else {
            $list = $shopRoomSetModel->where('time', '')->where('room_id', $room_id)->order('hour', 'asc')->select();

        }

        $this->success('', $list);
    }

    /**
     * 删除套餐项
     */
    public function removeRoomSetItem()
    {

        $user = $this->auth->getUser();
        $id = $this->request->param('id');
        $shopRoomSetModel = new Shoproomset();
        $shopModel = new \app\admin\model\Shop();
        $roomSet = $shopRoomSetModel->where('id', $id)->find();
        $shop = $shopModel->where('user_id', $user['id'])->where('id', $roomSet['shop_id'])->find();
        if (!$shop) {
            $this->error("无权限操作");
        }
        $shopRoomSetModel->where('id', $id)->delete();

        $this->success('操作成功');
    }


    public function getRoomCodeUrl()
    {

        $user = $this->auth->getUser();
        $room_id = $this->request->param('room_id');


        $roomModel = new \app\admin\model\Shoproom();
        $room = $roomModel->where('id', $room_id)->find();

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();

        $orgModel = new Org();
        $org = $orgModel->where('id', $shop['org_id'])->find();

        $app_id = $org['app_id'];
        $app_secret = $org['app_secret'];


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $app_id . "&secret=" . $app_secret;
        $ret = Http::get($url);
        $obj = json_decode($ret, true);
        $token = $obj['access_token'];

        $scene = $shop['id'] . "-" . $room_id;
        error_log("==scene===" . $scene);

        $url2 = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=$token";
        $data = [
            'scene' => $scene,
            'page' => 'pages/order/submit',

        ];
        $name = "qx_saas_room_" . $room_id;

        $data = json_encode($data);
        //拿到二维码
        $result = Http::post($url2, $data);

        $base64 = base64_encode($result);
        $mime = "image/png";
        $img = 'data:' . $mime . ';base64,' . $base64;
        $filename = './uploads/' . $name . '.jpg';

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }

        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {

            if ($room['qr_code'] != '') {

                $url = cdnurl($room['qr_code'], true);
            } else {

                base64_image_content($img, $filename);

                $per = 0.5;
                list($width, $height) = getimagesize($filename);
                $n_w = $width * $per;
                $n_h = $height * $per;
                $new = imagecreatetruecolor($n_w, $n_h);
                $img = imagecreatefromjpeg($filename);
//拷贝部分图像并调整
                imagecopyresized($new, $img, 0, 0, 0, 0, $n_w, $n_h, $width, $height);
//图像输出新图片、另存为
                imagedestroy($new);
                imagedestroy($img);

                $config = get_addon_config('alioss');
                $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
                $ret = $oss->uploadFile($config['bucket'], $name . ".jpg", $filename);
                $url = $ret['info']['url'];

                $roomModel->where('id', $room_id)->update(['qr_code' => "/" . $name . ".jpg"]);
                error_log("==oss=ret==" . json_encode($ret));

            }


            $url = cdnurl("/" . $name . ".jpg", true);
            $this->success('', $url);
        }

    }


    public function deleteRoom()
    {

        $room_id = $this->request->param('room_id');
        $shopRoomModel = new Shoproom();
        $shopRoomModel->where('id', $room_id)->delete();
        $shopDeviceModel = new Shopdevice();
        $shopDeviceModel->where('room_id', $room_id)->update(['room_id' => -1, 'bind_status' => -1]);

        $this->success('成功');

    }

    /**
     */
    public function getMaxHour()
    {

        $shop_id = $this->request->param('shop_id');

        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $shop_id)->find();

        //判断，0抽佣店铺放开后台开包厢开包箱(最多8小时)
        if($shop['profit_type'] == 1){
            $max_hour = $shop['max_hour'];
        }else{
            $max_hour = 2;
        }

        $ret = array();
        $obj = array();
        $obj['hour'] = "10分钟";
        $obj['sec'] = 600;
        $ret[] = $obj;

        $obj = array();
        $obj['hour'] = "30分钟";
        $obj['sec'] = 1800;
        $ret[] = $obj;

        for ($i = 1; $i <= $max_hour; $i++) {

            if ($i < 10) {
                $obj = array();
                $obj['hour'] = $i . "小时";
                $obj['sec'] = $i * 3600;
                $ret[] = $obj;
            }

        }

        $this->success('', $ret);
    }


}
